package sky.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import sky.domain.Country;
import sky.service.CountryService;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 20.05.13
 * Time: 13:16
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class CountryController {

    @Autowired
    private CountryService countryService;

    @RequestMapping(value = "/country", method = RequestMethod.GET)
    public String countryInfo(@RequestParam("id") Integer id, Map<String, Object> map) {
        map.put("country", countryService.getCountryById(id));
        return "country";
    }

    @RequestMapping(value = "/countries", method = RequestMethod.GET)
    public String countries(Map<String, Object> map) {
        map.put("country", new Country());
        map.put("countryList", countryService.listCountry());
        return "countries";
    }

    @ModelAttribute("showAuth")
    public Integer getAuth() {
        for (GrantedAuthority authority: getAuthentication().getAuthorities()) {
            if (authority.getAuthority().equals("ROLE_USER")) {
                return 1;
            }
            if (authority.getAuthority().equals("ROLE_ADMIN")) {
                return 2;
            }
        }
        return 0;
    }

    protected Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
